<template>
	<view :style="[{paddingTop:CustomBar+'px'}]">
		<cu-custom bgColor="bg-colorP" :fatherCss="'box-shadow: none'" :isBack="isBack" :isHome="isHome">
			<block slot="backText"></block>
			<block slot="content">支付</block>
		</cu-custom>
		<view class="head">
			<image class="bg" src="https://xarkbucket.oss-cn-hangzhou.aliyuncs.com/%E5%85%8D%E5%8D%95%E9%80%9AApp/pay-head.png"
			 mode=""></image>
			<view class="bus-info">
				<image :src="info.shop_image?info.shop_image:info.headimg" mode=""></image>
				<view class="">
					<text>向</text>　{{info.name}}　<text>付钱</text>
				</view>
			</view>
		</view>
		<view class="pay">
			<view class="title">
				请输入金额
			</view>
			<view class="input-cont">
				<text>¥</text>
				<input type="text" v-model="price" placeholder="0.00" disabled="true" @tap="showVK" placeholder-class="place-hl"
				 redo />
			</view>
		</view>
		<view class="use-btn" :class="hasNum?'active':''" @click="submit">
			确认支付
		</view>
		<v-keyboard ref="keyboard" :digital="true" :disorderly="false" @typing="typing" @enter="submit"></v-keyboard>
	</view>
</template>

<script>
	import vKeyboard from './component/VKeyboard/VKeyboard.vue'
	export default {
		components: {
			vKeyboard
		},
		data() {
			return {
				CustomBar: this.CustomBar,
				busId: '',
				info: {},
				price: '',
				hasNum: false,
				resultShow: false,
				scrollH: '',
				windowSize: '',
				animationResult: {},
				// 15元以上为true
				isFif: false,
				distributionUserId: '',
				isHome: false,
				isBack: false
			}
		},
		onReady() {
			this.$refs.keyboard.activate();
			
		},
		onLoad(options) {
			// options.id = '1'
			// 判断显示返回首页还是上一步
			var that = this
			var length = getCurrentPages().length
			if (length == 1) {
				this.isHome = true
			} else {
				this.isBack = true
			}
			
			if (options.id) {
				uni.setStorageSync('shopPayId', options.id)
			} else if (options.scene) {
				uni.setStorageSync('shopPayId', options.scene)
			}else{
				uni.setStorageSync('shopPayId', '')
			}
			
			if (!uni.getStorageSync('auth_token')) {
				let curUrl = `/${this.curUrlWithArgs()}`
				curUrl = encodeURIComponent(curUrl)
				uni.redirectTo({
					url: `/pages/login?next=${curUrl}`,
				})
				return
			} else {
				// #ifdef H5
				var href = window.location.href
				if (href.indexOf('code') > -1) {
					var zIndex = window.location.href.slice(window.location.href.indexOf('?'), window.location.href.indexOf('#'))
					window.location.href = window.location.href.split(zIndex).join('')
				}
				// #endif
			}
			// #ifdef H5
			this.wxConfig()
			// #endif
			// 拆分
			if(uni.getStorageSync('shopPayId')){
				var shopPayId = uni.getStorageSync('shopPayId')
				if(shopPayId.indexOf('-') > -1){
					this.busId = shopPayId.split('-')[0]
					this.distributionUserId = shopPayId.split('-')[1]
				}else{
					this.busId = shopPayId
				}
			}
			this.getBusInfo()

			uni.getSystemInfo({
				success: (res) => {
					this.scrollH = res.windowHeight
					this.windowSize = res
				}
			})
		},
		methods: {
			showVK() {
				this.$refs.keyboard.activate();
			},
			typing(val) {
				if (!val.backspace) {
					this.price += val.char
				} else {
					this.price = this.price.slice(0, this.price.length - 1)
				}
			},
			/*获取当前页带参数的url*/
			curUrlWithArgs() {
				var pages = getCurrentPages()
				var currentPage = pages[pages.length - 1]
				var url = currentPage.route
				var options = currentPage.options
				var urlWithArgs = url + '?'
				for (var key in options) {
					var value = options[key]
					urlWithArgs += key + '=' + value + '&'
				}
				urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
				return urlWithArgs
			},
			/**配置jsApi**/
			wxConfig() {
				var that = this
				let system = uni.getSystemInfoSync(); // 获取系统信息
				var url = ''
				if (system.platform === 'android') { // 判断平台
					url = window.location.href
				} else {
					url = encodeURIComponent(window.location.href.split('#')[0])
				}
				this.$request({
					url: '/JsTicket/getSignPackage',
					data: {
						'url': url,
					},
					success: res => {
						var result = res.data.data
						that.$wx.config({
							debug: false, // 开启调试模式,调用的所有api的返回值会在客户端console.log出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
							appId: result.appId, // 必填，公众号的唯一标识
							timestamp: result.timestamp, // 必填，生成签名的时间戳
							nonceStr: result.nonceStr, // 必填，生成签名的随机串
							signature: result.signature, // 必填，签名
							jsApiList: [
								'checkJsApi',
								'chooseWXPay',
							] // 必填，需要使用的JS接口列表
						});
						uni.hideLoading()
					},
					fail: () => {},
					complete: () => {}
				});
			},
			getBusInfo() {
				var that = this
				this.$request({
					url: '/Consumer/pay_page_new',
					data: {
						business_id: that.busId
					},
					success: res => {
						if (res.data.status == 1) {
							var result = res.data.data
							that.info = result
						}
						uni.hideLoading()
					},
					fail: () => {},
					complete: () => {}
				});
			},
			submit() {
				var that = this
				var isNum = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
				var price = this.price
				var busId = this.busId
				if (!this.hasNum) {
					uni.showToast({
						title: '请输入支付金额',
						icon: 'none'
					})
					return false
				} else if (!isNum.test(price)) {
					uni.showToast({
						title: '请保留小数点后两位',
						icon: 'none'
					})
					return false
				}
				this.$request({
					url: '/Order/orderPay',
					data: {
						'business_id': busId,
						'money': price,
						'distribution_user_id': that.distributionUserId
					},
					success: res => {
						if (res.data.status == 1) {
							var result = res.data.data
							// #ifdef H5
							that.$wx.checkJsApi({
								jsApiList: [
									'chooseWXPay'
								],
								success: function(res) {
									that.$wx.chooseWXPay({
										appId: result.appId,
										timestamp: result.timeStamp,
										nonceStr: result.nonceStr,
										package: result.package,
										signType: result.signType,
										paySign: result.paySign,
										success: function(log) {
											if (log.errMsg == 'chooseWXPay:ok') {
												uni.navigateTo({
													url: '/pages/offlinePaySuc?price=' + price + '&busName=' + that.info.name + '&orderId=' +
														result.order_id + '&payType=offline&busId=' + that.busId+'&mode='+that.info.mode,
													success: log => {
														uni.removeStorageSync('shopPayId')
													}
												});
											}
										},
										fail(err) {
											uni.showToast({
												title: '支付失败',
												mask: true
											});
										}
									})

									if (res.checkResult.chooseWXPay == false) {
										alert('你的微信版本太低，不支持微信JS接口，请升级到最新的微信版本！')
									}
								}
							})
							// #endif
							// #ifdef MP-WEIXIN
							uni.requestPayment({
								'timeStamp': result.timeStamp,
								'nonceStr': result.nonceStr,
								'package': result.package,
								'signType': result.signType,
								'paySign': result.paySign,
								success: function success(res) {
									uni.showToast({
										title: '支付成功'
									})
									setTimeout(function() {
										uni.navigateTo({
											url: '/pages/offlinePaySuc?price=' + price + '&busName=' + that.info.name + '&orderId=' +
												result.order_id + '&payType=offline&busId=' + that.busId+'&mode='+that.info.mode,
											success: log => {
												uni.removeStorageSync('shopPayId')
											}
										});
									}, 1000)
								},
								fail: function success(err) {
									uni.showToast({
										title: '支付失败'
									})
								}
							});
							// #endif
						}
						uni.hideLoading()
					},
					fail: () => {},
					complete: () => {}
				});

			}
		},
		watch: {
			'price'(newVale, oldVale) {
				this.hasNum = newVale == '' ? false : true
			}
		}
	}
</script>


<style>
	page {
		background: #fff;
	}
</style>
<style scoped>
	.head {
		width: 100%;
		height: 300rpx;
		position: relative;

	}

	.head .bg {
		width: 100%;
		height: 300rpx;
		position: absolute;
		top: 0;
		left: 0;
		z-index: 1;
	}

	.bus-info {
		width: 100%;
		z-index: 2;
		height: 260rpx;
		position: absolute;
		bottom: 30rpx;
		left: 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.bus-info image {
		width: 160rpx;
		height: 160rpx;
		border-radius: 16rpx;
	}

	.bus-info>view {
		display: flex;
		align-items: center;
		margin-top: 20rpx;
		font-size: 30rpx;
		color: #ffffff;
		font-weight: bold;
	}

	.bus-info>view>text {
		font-weight: normal;
	}

	.pay {
		width: 100%;
		box-sizing: border-box;
		padding: 0 40rpx;
	}

	.pay .title {
		line-height: 36px;
		font-size: 30rpx;
		letter-spacing: 1px;
		color: #333333;
		letter-spacing: 1rpx;
		font-weight: bold;
	}

	.pay .input-cont {
		width: 100%;
		height: 100rpx;
		display: flex;
		background-color: #f5f5f5;
		border-radius: 8px;
		padding: 20rpx 30rpx;
		box-sizing: border-box;
	}

	.pay .input-cont text {
		color: #333;
		font-weight: bold;
		font-size: 40rpx;
	}

	.pay .input-cont input {
		height: 60rpx !important;
		flex: 1;
		color: #333;
		font-size: 48rpx;
		line-height: 60rpx !important;
		padding-left: 20rpx;
		box-sizing: border-box;
	}

	.place-hl {
		color: #999;
	}

	.use-btn {
		width: 560rpx;
		height: 88rpx;
		background-color: rgba(243, 73, 48, .5);
		border-radius: 44rpx;
		color: #fff;
		text-align: center;
		line-height: 88rpx;
		margin-top: 88rpx;
		margin: 88rpx auto;
		;
	}

	.use-btn.active {
		background-color: rgba(243, 73, 48, 1);
	}
</style>
